package com.homework.decoder;

import com.homework.service.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.ByteProcessor;
import org.apache.logging.log4j.util.Chars;

import java.nio.charset.Charset;
import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;

    private Serializer serializer;

    public RpcDecoder(Class<?> clazz,Serializer serializer){
        System.out.println("RpcDecoder ......");
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        System.out.println("RpcDecoder decode ............");
        // 类型为null或者不是客户端传过来的字节块长度
        if (clazz == null || byteBuf.readableBytes() < 4){
            return;
        }
        //标记当前读的index
        byteBuf.markReaderIndex();
        //通信的消息头
        int size = byteBuf.readInt();
        //如果消息体长度小于0时直接关闭连接
        if (size < 0){
            channelHandlerContext.close();
        }
        //读到的消息长度小于传过来的消息长度,重置
        if (byteBuf.readableBytes() < size){
            byteBuf.resetReaderIndex();
            return;
        }
        byte[] data = new byte[size];
        byteBuf.readBytes(data);
        System.out.println("到我这里了");
        list.add(serializer.deserialize(clazz,data));
    }
}
